<?php
/**
 * 更新股票列表
 */

$url = 'http://www.cninfo.com.cn/jsnew/stocklist_stock.js?COLLCC=' . mt_rand();
$ch  = curl_init();
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url);
$response = curl_exec($ch);
curl_close($ch);

if (empty($response))
{
    echo "股票列表JS文件下载失败: {$url}\n";
    exit;
}

$matches = array();
preg_match_all('/\|([A-Z].*?):\-([0-9].*?)\-(.*?)\|/', $response, $matches); // |YDLA:-000539-粤电力Ａ|
if ( ! isset($matches[2]))
{
    echo "股票列表JS数据提取失败\n";
    exit;
}

//======= 记录股票列表数据开始 =======//
$list = array();

foreach ($matches[2] as $key => $code)
{
    $pinyin = '';
    if (isset($matches[1][$key]))
    {
        $pinyin = iconv('GB2312', 'UTF-8//IGNORE', $matches[1][$key]); // 股票拼音
    }

    $name     = iconv('GB2312', 'UTF-8//IGNORE', $matches[3][$key]);  // 股票名称GBK转换为UTF-8
    $first    = substr($code, 0, 1); // 截取股票代码第一位
    if (in_array($first, array(2, 9))) continue; // 忽略B股
    $exchange = ($first > 3) ? 'SH' : 'SZ';
    $list[]   = array('name' => $name, 'code' => $exchange . $code);
}

$file = __DIR__ . '/../data/list.json';
file_put_contents($file, json_encode($list));

echo "股票列表更新完成\n";

